<template>
  <div class="order-list-page">
    <!-- 订单汇总 -->
    <el-card class="summary-card">
      <div class="summary-content">
        <div class="summary-item">
          <div class="summary-label">今日订单数</div>
          <div class="summary-value">{{ orderSummary.todayOrders || 0 }}</div>
        </div>
        <div class="summary-item">
          <div class="summary-label">总订单数</div>
          <div class="summary-value">{{ orderSummary.totalOrders || 0 }}</div>
        </div>
        <div class="summary-item">
          <div class="summary-label">总销售额</div>
          <div class="summary-value">¥{{ orderSummary.totalSales?.toFixed(2) || '0.00' }}</div>
        </div>
      </div>
    </el-card>

    <!-- 订单列表 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>订单列表</span>
          <div class="header-actions">
            <el-select
              v-model="statusFilter"
              placeholder="订单状态"
              class="status-select"
              clearable
            >
              <el-option label="待结账" :value="0" />
              <el-option label="已结账" :value="1" />
              <el-option label="已取消" :value="2" />
            </el-select>
            <el-button 
              type="text"
              @click="refreshOrders"
            >
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-table :data="orders" style="width: 100%">
        <el-table-column prop="id" label="订单ID" width="80" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="总金额" />
        <el-table-column prop="createTime" label="创建时间">
          <template #default="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button 
              v-if="scope.row.status === 0"
              size="small" 
              type="success"
              @click="payOrder(scope.row.id)"
            >
              结账
            </el-button>
            <el-button 
              v-if="scope.row.status === 0"
              size="small" 
              type="danger"
              @click="cancelOrder(scope.row.id)"
            >
              取消
            </el-button>
            <el-button
              size="small"
              type="primary"
              @click="showOrderDetail(scope.row.id)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- Order Detail Dialog -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="50%"
    >
      <div v-if="orderDetail" class="order-detail">
        <div class="detail-item">
          <span class="label">订单编号：</span>
          <span>{{ orderDetail.order.orderNo }}</span>
        </div>
        <div class="detail-item">
          <span class="label">状态：</span>
          <el-tag :type="getStatusType(orderDetail.order.status)">
            {{ getStatusText(orderDetail.order.status) }}
          </el-tag>
        </div>
        <div class="detail-item">
          <span class="label">创建时间：</span>
          <span>{{ formatTime(orderDetail.order.createTime) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">更新时间：</span>
          <span>{{ formatTime(orderDetail.order.updateTime) }}</span>
        </div>
        <div class="detail-items">
          <h4>订单菜品</h4>
          <div 
            v-for="item in orderDetail.details" 
            :key="item.id" 
            class="detail-item"
          >
            <span class="item-name">{{ item.dishName }}</span>
            <span class="item-quantity">x{{ item.quantity }}</span>
            <span class="item-price">¥{{ item.dishPrice }}</span>
          </div>
        </div>
        <div class="detail-item total">
          <span class="label">总金额：</span>
          <span class="total-amount">¥{{ orderDetail.totalAmount }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { orderApi } from '../api'

// State
const orders = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const statusFilter = ref('')
const detailDialogVisible = ref(false)
const orderDetail = ref(null)

// Order summary state
const orderSummary = ref({
  todayOrders: 0,
  totalOrders: 0,
  totalSales: 0
})

// Add total pages state
const pages = ref(0)

// Methods
const loadOrders = async () => {
  try {
    const response = await orderApi.getOrderList(
      currentPage.value,
      pageSize.value,
      statusFilter.value ? Number(statusFilter.value) : undefined
    )
    orders.value = response.data.records
    total.value = response.data.total
    // Update total pages
    pages.value = response.data.pages
  } catch (error) {
    ElMessage.error('加载订单列表失败')
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // Reset to first page when changing page size
  loadOrders()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadOrders()
}

const showOrderDetail = async (id) => {
  try {
    const response = await orderApi.getOrderDetail(id)
    orderDetail.value = response.data
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取订单详情失败')
  }
}

const payOrder = async (id) => {
  try {
    await orderApi.payOrder(id)
    ElMessage.success('支付成功')
    loadOrders()
  } catch (error) {
    ElMessage.error('支付失败')
  }
}

const cancelOrder = async (id) => {
  try {
    await ElMessageBox.confirm('确定要取消这个订单吗？', '提示', {
      type: 'warning'
    })
    await orderApi.cancelOrder(id)
    ElMessage.success('订单已取消')
    loadOrders()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消订单失败')
    }
  }
}

const getStatusType = (status) => {
  switch (status) {
    case 0:
      return 'warning'
    case 1:
      return 'success'
    case 2:
      return 'info'
    default:
      return ''
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 0:
      return '待结账'
    case 1:
      return '已结账'
    case 2:
      return '已取消'
    default:
      return status
  }
}

const formatTime = (timeString) => {
  if (!timeString) return ''
  const date = new Date(timeString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  })
}

// Order summary methods
const loadOrderSummary = async () => {
  try {
    const response = await orderApi.getOrderSummary()
    orderSummary.value = response.data
  } catch (error) {
    ElMessage.error('加载订单汇总失败')
  }
}

// Add refresh method
const refreshOrders = async () => {
  try {
    await Promise.all([
      loadOrders(),
      loadOrderSummary()
    ])
    ElMessage.success('刷新成功')
  } catch (error) {
    ElMessage.error('刷新失败')
  }
}

// Lifecycle
onMounted(() => {
  loadOrders()
  loadOrderSummary()
})
</script>

<style scoped>
.order-list-page {
  padding: 20px;
  min-height: 100vh;
}

.summary-card {
  margin-bottom: 20px;
}

.summary-content {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  padding: 20px 0;
}

.summary-item {
  flex: 1;
  min-width: 150px;
  text-align: center;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.summary-label {
  color: #666;
  font-size: 14px;
  margin-bottom: 10px;
}

.summary-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.summary-item:last-child .summary-value {
  color: #f56c6c;
}

.card-header {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

@media (min-width: 768px) {
  .card-header {
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.status-select {
  width: 120px;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .order-list-page {
    padding: 10px;
  }

  .summary-content {
    flex-direction: column;
  }

  .summary-item {
    min-width: 100%;
  }

  .status-select {
    width: 100px;
  }

  .el-table {
    font-size: 12px;
  }

  .el-button {
    padding: 8px 12px;
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.order-detail {
  padding: 20px;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.detail-item .label {
  width: 100px;
  color: #666;
}

.detail-items {
  margin: 20px 0;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.detail-items h4 {
  margin: 0 0 15px 0;
  color: #333;
}

.detail-item.total {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 2px solid #eee;
}

.total-amount {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
}

.item-name {
  flex: 1;
}

.item-quantity {
  margin: 0 10px;
  color: #666;
}

.item-price {
  color: #f56c6c;
  font-weight: bold;
  min-width: 60px;
  text-align: right;
}
</style> 